package com.marion.langchain4jdemo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索服务类
 */
@Slf4j
@Service
public class SearchService {

    private static final String SEARCH_URL = "https://s.lenovo.com.cn/search/v2?specifiedType=0&trackId=88B78345-D3D4-44BF-B560-29EC2C82B8D2&pageSize=20&refresh=true&isProprietary=false&isPersonal=false&isInstallment=false&isOldForNew=false&lenovoId=10181092268&pageType=%E9%A6%96%E9%A1%B5&isReturnNPrice=false&shopid=1&stort=0&plat=7&page=1&keyType=%E6%9C%80%E8%BF%91%E6%90%9C%E7%B4%A2%E8%AF%8D&key={key}&isStock=false&isO2O=false";

    private final RestTemplate restTemplate;

    public SearchService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Tool(description = "根据商品名称关键字搜索商品")
    public List<JSONObject> searchProducts(@ToolParam(required = true, description = "商品名称关键字") String keyword) {
        log.info("Searching products with key: {}", keyword);
        List<JSONObject> products = new ArrayList<>();
        try {
            // 发起 HTTP GET 请求
            String response = restTemplate.getForObject(SEARCH_URL, String.class, keyword);
            log.info("Search response: {}", response);

            // 使用 fastjson 解析 JSON 响应
            JSONObject jsonObject = JSON.parseObject(response);
            JSONArray itemsArray = jsonObject.getJSONArray("items");

            // 将 items 数组映射为 Product 列表
            if (itemsArray != null) {
                for (int i = 0; i < itemsArray.size(); i++) {
                    JSONObject item = itemsArray.getJSONObject(i);
                    products.add(item);
                }
            }
        } catch (Exception e) {
            log.error("Error occurred while searching products: {}", e.getMessage(), e);
        }
        return products;
    }
}
